package com.ship.system.controller;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ship.common.core.base.Page;
import com.ship.common.core.domain.R;
import com.ship.common.core.enums.ModuleTypeEnum;
import com.ship.common.core.exception.BusException;
import com.ship.common.core.utils.DateUtils;
import com.ship.common.core.utils.StringUtils;
import com.ship.common.core.utils.poi.ExcelUtil;
import com.ship.common.core.web.domain.BaseResultCode;
import com.ship.common.core.web.domain.JsonResult;
import com.ship.common.log.annotation.Log;
import com.ship.common.log.enums.BusinessType;
import com.ship.common.security.utils.SecurityUtils;
import com.ship.system.api.RemoteFileService;
import com.ship.system.api.domain.SysDept;
import com.ship.system.api.domain.SysFile;
import com.ship.system.api.domain.SysUserNew;
import com.ship.system.domain.SysMessage;
import com.ship.system.domain.SysMessageConfig;
import com.ship.system.service.SysMessageConfigService;
import com.ship.system.service.SysMessageService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.LinkedList;
import java.util.List;
import java.util.Properties;
import java.util.stream.Collectors;

/**
 * 系统消息列表管理
 * 
 * @author zhangyh
 */
@RestController
@RequestMapping("/message")
@Api(value = "sysMessage", tags = "系统消息列表管理")
public class SysMessageController
{
    @Autowired
    private SysMessageService sysMessageService;

    @Resource
    private RemoteFileService remoteFileService;

    @Value("${file_server.host}")
    private String fileServerHost;

    /**
     * 测试邮件
     */
    @ApiOperation(value = "测试邮件")
    @GetMapping("/testMail/{toAdd}")
    public JsonResult testMail(@PathVariable(value = "toAdd") String toAdd){
        // 发件人电子邮件地址
        String from = "sy_cbdd@cnooc.com.cn";

        // SMTP服务器地址
        String host = "cmail.cnooc.com.cn";

        if(StringUtils.equals("1",toAdd)){
            toAdd = "huangzx5@cnooc.com.cn";
        }

//        // 获取系统属性
//        Properties properties = System.getProperties();
//
//        // 设置邮件服务器
//        properties.setProperty("mail.smtp.host", host);
//        properties.setProperty("mail.smtp.port", "25");
//
//        // 获取默认的Session对象
//        Session session = Session.getDefaultInstance(properties);
//
//        try {
//            // 创建默认的MimeMessage对象
//            MimeMessage message = new MimeMessage(session);
//
//            // 设置 From: 头部字段
//            message.setFrom(new InternetAddress(from));
//
//            // 设置 To: 头部字段
//            message.addRecipient(Message.RecipientType.TO, new InternetAddress(toAdd));
//
//            // 设置 Subject: 头部字段
//            message.setSubject("LNG船舶调度系统测试邮件发送功能-我是标题");
//
//            // 现在设置实际消息
//            message.setText("LNG船舶调度系统测试邮件发送功能-我是内容");
//
//            // 发送消息
//            Transport.send(message);
//            System.out.println("Sent message successfully....");
//            return JsonResult.success();
//        } catch (MessagingException mex) {
//            mex.printStackTrace();
//            return JsonResult.failed(mex.getMessage());
//        }


        // 获取系统属性
        Properties properties = System.getProperties();

        // 设置邮件服务器
        properties.setProperty("mail.smtp.host", host);
        properties.setProperty("mail.smtp.port", "25"); // 或者465，取决于你的SMTP服务器配置
        properties.setProperty("mail.smtp.auth", "true");
        properties.setProperty("mail.smtp.starttls.enable", "true"); // 如果使用TLS

        // 获取默认的Session对象
        Session session = Session.getDefaultInstance(properties, new Authenticator() {
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(from, "W!injrt9nv2kdea");
            }
        });

        try {
            // 创建默认的MimeMessage对象
            MimeMessage message = new MimeMessage(session);

            // 设置发件人
            message.setFrom(new InternetAddress(from));

            // 设置收件人
            message.addRecipient(Message.RecipientType.TO, new InternetAddress(toAdd));

            // 设置 Subject: 头部字段
            message.setSubject("LNG船舶调度系统测试邮件发送功能-我是标题");

            // 现在设置实际消息
            message.setText("LNG船舶调度系统测试邮件发送功能-我是内容");

            // 发送消息
            Transport.send(message);
            System.out.println("Sent message successfully....");
            return JsonResult.success();
        } catch (MessagingException mex) {
            System.out.println(mex.getMessage());
            mex.printStackTrace();
            return JsonResult.failed(mex.getMessage());
        }

    }

    public static void main(String[] args) {

        // 发件人电子邮件地址
        String from = "sy_cbdd@cnooc.com.cn";
        String to = "sy_cbdd@cnooc.com.cn";

        // SMTP服务器地址
        String host = "cmail.cnooc.com.cn";

        // 获取系统属性
        Properties properties = System.getProperties();

        // 设置邮件服务器
        properties.setProperty("mail.smtp.host", host);
        properties.setProperty("mail.smtp.port", "25");
        properties.setProperty("mail.smtp.debug", "true");

        // 获取默认的Session对象
        Session session = Session.getDefaultInstance(properties);

        try {
            // 创建默认的MimeMessage对象
            MimeMessage message = new MimeMessage(session);

            // 设置发件人
            message.setFrom(new InternetAddress(from));

            // 设置收件人
            message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));

            // 设置邮件主题
            message.setSubject("哈哈哈哈哈哈哈哈哈哈!");

            // 设置邮件内容
            message.setText("啊搜房好iu是符号iu神佛i啊是佛啊是佛啊");

            // 发送消息
            Transport.send(message);
            System.out.println("Sent message successfully....");
        } catch (MessagingException mex) {
            System.out.println(mex.getMessage());
            mex.printStackTrace();
        }
    }

    /**
     * 获取消息详情
     */
    @ApiOperation(value = "获取消息详情")
    @GetMapping("/detail/{messageId}")
    public JsonResult<SysMessage> getDetail(@PathVariable(value = "messageId") Long messageId){
        return sysMessageService.getDetail(messageId);
    }

    /**
     * 获取当前用户未读消息数量
     */
    @ApiOperation(value = "获取当前用户未读消息数量")
    @GetMapping("/unread/count")
    public JsonResult getUnreadCount(){
        return sysMessageService.getUnreadCount();
    }

    /**
     * 任务完成
     */
    @ApiOperation(value = "任务完成")
    @GetMapping("/finish/{messageId}")
    public JsonResult finishTask(@PathVariable(value = "messageId") Long messageId){
        return sysMessageService.finishTask(messageId);
    }

    /**
     * 消息分页
     */
    @ApiOperation(value = "消息分页")
    @PostMapping("/page")
    public JsonResult<Page<SysMessage>> getPage(@RequestBody SysMessage message){
        if(message.getNoticeUid() == null){
            message.setNoticeUid(SecurityUtils.getUserId());
        }
        Page<SysMessage> resultPage = sysMessageService.page(message,new QueryWrapper<>());
        return JsonResult.success(resultPage);
    }

    /**
     * 工作台任务/消息查询
     */
    @ApiOperation(value = "工作台任务/消息查询")
    @PostMapping("/list")
    public JsonResult<List<SysMessage>> getWorkBranchMessageList(@RequestBody SysMessage message){
        if(message.getNoticeUid() == null){
            message.setNoticeUid(SecurityUtils.getUserId());
        }
        LambdaQueryWrapper<SysMessage> queryWrapper = new LambdaQueryWrapper<>(message);
        if(message.getMessageStatus() != null && message.getMessageStatus().intValue() == 1){
            queryWrapper.orderByAsc(SysMessage::getReadStatus);
            queryWrapper.orderByDesc(SysMessage::getNoticeTime);
        }
        if(message.getTaskStatus() != null && message.getTaskStatus().intValue() == 1){
            queryWrapper.orderByAsc(SysMessage::getFinishStatus);
            queryWrapper.orderByDesc(SysMessage::getNoticeTime);
        }
        if(message.getPageSize() != null){
            queryWrapper.last("limit "+message.getPageSize());
        }

        List<SysMessage> resultList = sysMessageService.getBaseMapper().selectList(queryWrapper);
        return JsonResult.success(resultList);
    }

    /**
     * 消息转为任务
     */
    @ApiOperation(value = "消息转为任务")
    @GetMapping("/exchange/{messageId}")
    public JsonResult exchange(@PathVariable(value = "messageId") Long messageId){
        return sysMessageService.exchangeTask(messageId);
    }

    /**
     * 消息导出
     */
    @ApiOperation(value = "消息导出")
    @Log(title = "消息管理", businessType = BusinessType.EXPORT)
    @PostMapping("/page/export")
    public JsonResult export(@RequestBody SysMessage message)
    {
        QueryWrapper queryWrapper = new QueryWrapper<>();
        if(message.getNoticeUid() == null){
            message.setNoticeUid(SecurityUtils.getUserId());
        }
        if (CollectionUtil.isNotEmpty(message.getIds())) {
            queryWrapper.in("id", message.getIds());
        }
        List<SysMessage> list = sysMessageService.pageExportList(message, queryWrapper,new LinkedList<>());
        for (SysMessage sysMessage : list) {
            if(sysMessage.getModuleType() != null){
                sysMessage.setModuleTypeString(ModuleTypeEnum.getValueByCode(sysMessage.getModuleType()));
            }
            if(sysMessage.getNoticeTime() != null){
                sysMessage.setNoticeTimeFormat(DateUtils.parseDateToStr("yyyy-MM-dd HH:mm:ss",sysMessage.getNoticeTime()));
            }
        }
        ExcelUtil<SysMessage> util = new ExcelUtil<SysMessage>(SysMessage.class);
        MultipartFile file = util.getExportExcelUrl(list, "消息数据",fileServerHost);
        if(file == null){
            return JsonResult.failed("文件解析失败！");
        }
        R<SysFile> result = remoteFileService.upload(file);
        if(result.getCode() != R.SUCCESS){
            throw new BusException("文件服务器连接失败", BaseResultCode.GENERAL_ERROR);
        }
        return JsonResult.success(result.getData().getHttpsUrl());
    }

}
